package cn.edu.zafu.bigdata.linfeifei.j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class StudentInfoManager {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://192.168.169.76:3306/learnjava?useSSL=false";
    private static final String USER = "learn";
    private static final String PASSWORD = "learnpassword";

    // 加载数据库驱动
    static {
        try {
            Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 建立数据库连接
    public Connection connect() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 添加学生信息
    public boolean addStudentInfo(StudentInfo student) {
        String sql = "INSERT INTO student_info (id, name, phone) VALUES (?, ?, ?)";
        try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, student.getId());
            pstmt.setString(2, student.getName());
            pstmt.setString(3, student.getPhone());
            int result = pstmt.executeUpdate();
            return result > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 主方法，用于测试添加学生信息
    public static void main(String[] args) {
        StudentInfoManager manager = new StudentInfoManager();
        StudentInfo student = new StudentInfo("001", "张三", "12345678901");
        boolean result = manager.addStudentInfo(student);
        if (result) {
            System.out.println("学生信息添加成功！");
        } else {
            System.out.println("学生信息添加失败！");
        }
    }
}